package org.devf.fork.imsimulator.socket.handler;

import cn.hutool.json.JSONUtil;
//import cn.hutool.log.Log;
import org.devf.fork.imsimulator.service.TokenMgr;
import org.devf.fork.imsimulator.socket.Channel;
import org.devf.fork.imsimulator.socket.Ihandler;
import org.devf.fork.imsimulator.socket.TcpClientFactory;
import org.devf.fork.imsimulator.socket.dto.BasePackets;
import org.devf.fork.imsimulator.socket.dto.BizType;
import org.devf.fork.imsimulator.socket.handler.listener.HandlerListener;
import org.devf.fork.imsimulator.socket.handler.listener.HeartListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * HeartHandler related
 *
 * @author wanghuafu
 * @since 1.0  2023/9/12 14:37
 */
public class HeartHandler implements Ihandler {
    private final List<HeartListener> chatListenerList = new ArrayList<>();
    private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

    @Override
    public boolean isSupport(BasePackets packets) {
        return packets.getBizType().equals(BizType.HEARTBEAT.name());
    }

    @Override
    public boolean execute(Channel channel, BasePackets packets) {
        return false;
    }

    @Override
    public void register(HandlerListener chatListener) {
        chatListenerList.add((HeartListener) chatListener);
    }

    public HeartHandler() {
        executorService.scheduleWithFixedDelay(() -> {
            if (TcpClientFactory.getDefaultTcpClient().isEmpty()) {
                System.out.println("待登录后发送心跳");
                return;
            }
            try {
                boolean isOk = sendHeartPackets();
                if (!isOk) {
                    System.out.println("心跳发送异常！！");
                    refreshView(new BasePackets(),false);
                } else {
                    refreshView(new BasePackets(),true);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, 1, 40, TimeUnit.SECONDS);

        System.out.println("心跳处理机制初始化成功");

    }

    public boolean sendHeartPackets() {
        BasePackets packets = new BasePackets();
        packets.setBizType(BizType.HEARTBEAT.name());
        packets.setIsNeedAck(0);
        packets.setFromDeviceId(TokenMgr.userModel.getDeviceId());
        return TcpClientFactory.getDefault().getChannel().write(JSONUtil.toJsonStr(packets));
    }

    private void refreshView(BasePackets packets,boolean result) {
        for (HeartListener chatListener : chatListenerList) {
            chatListener.heart(result);
        }
    }
}
